package com.example.icar.rosmaster;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Rosmaster WiFi类，用于处理WiFi相关功能
 */
public class RosmasterWifi {
    private static final String TAG = "RosmasterWifi";
    
    private Context context;
    private RosmasterLib rosmasterLib;
    private boolean debug = false;
    
    private ServerSocket serverSocket;
    private ExecutorService executorService;
    private boolean isServerRunning = false;
    
    // 回调接口
    public interface ServerCallback {

        void onClientConnected(Socket clientSocket);
        void onClientDisconnected();
        void onDataReceived(String data);
        void onServerError(String errorMessage);
    }
    
    private ServerCallback callback;
    
    /**
     * 构造函数
     * @param rosmasterLib Rosmaster库实例
     * @param debug 是否开启调试模式
     */
    public RosmasterWifi(RosmasterLib rosmasterLib, boolean debug) {
        this.rosmasterLib = rosmasterLib;
        this.debug = debug;
        this.executorService = Executors.newCachedThreadPool();
    }
    
    /**
     * 初始化
     * @param context 上下文
     */
    public void init(Context context) {
        this.context = context;
    }
    
    /**
     * 设置服务器回调
     * @param callback 回调接口
     */
    public void setServerCallback(ServerCallback callback) {
        this.callback = callback;
    }
    
    /**
     * 获取本地IP地址
     * @return IP地址字符串
     */
    public String getLocalIpAddress() {
        if (context == null) {
            Log.e(TAG, "Context is null, call init() first");
            return "0.0.0.0";
        }
        
        try {
            WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            if (wifiManager != null) {
                WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                int ipAddress = wifiInfo.getIpAddress();
                return String.format("%d.%d.%d.%d",
                        (ipAddress & 0xff),
                        (ipAddress >> 8 & 0xff),
                        (ipAddress >> 16 & 0xff),
                        (ipAddress >> 24 & 0xff));
            }
        } catch (Exception e) {
            Log.e(TAG, "获取IP地址错误: " + e.getMessage());
        }
        
        return "0.0.0.0";
    }
    
    /**
     * 启动TCP服务器
     * @param port 端口
     * @return 是否成功启动
     */
    public boolean startTcpServer(final int port) {
        if (isServerRunning) {
            Log.w(TAG, "TCP服务器已在运行");
            return false;
        }
        
        executorService.execute(() -> {
            try {
                serverSocket = new ServerSocket(port);
                isServerRunning = true;
                
                if (debug) {
                    Log.d(TAG, "TCP服务器已启动，监听端口: " + port);
                }
                
                while (isServerRunning) {
                    try {
                        // 等待客户端连接
                        Socket clientSocket = serverSocket.accept();
                        
                        if (debug) {
                            Log.d(TAG, "客户端已连接: " + clientSocket.getInetAddress().getHostAddress());
                        }
                        
                        // 通知客户端连接
                        if (callback != null) {
                            callback.onClientConnected(clientSocket);
                        }
                        
                        // 处理客户端连接
                        handleClientConnection(clientSocket);
                        
                    } catch (IOException e) {
                        if (isServerRunning) {
                            Log.e(TAG, "接受连接错误: " + e.getMessage());
                            if (callback != null) {
                                callback.onServerError("接受连接错误: " + e.getMessage());
                            }
                        }
                    }
                }
                
            } catch (IOException e) {
                Log.e(TAG, "启动TCP服务器错误: " + e.getMessage());
                isServerRunning = false;
                
                if (callback != null) {
                    callback.onServerError("启动TCP服务器错误: " + e.getMessage());
                }
            }
        });
        
        return true;
    }
    
    /**
     * 处理客户端连接
     * @param clientSocket 客户端Socket
     */
    private void handleClientConnection(final Socket clientSocket) {
        executorService.execute(() -> {
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true);
                
                String line;
                while (isServerRunning && !clientSocket.isClosed() && (line = reader.readLine()) != null) {
                    if (debug) {
                        Log.d(TAG, "收到数据: " + line);
                    }
                    
                    // 处理接收到的命令
                    String response = processCommand(line);
                    
                    // 发送响应
                    if (response != null) {
                        writer.println(response);
                        if (debug) {
                            Log.d(TAG, "发送响应: " + response);
                        }
                    }
                    
                    // 通知数据接收
                    if (callback != null) {
                        callback.onDataReceived(line);
                    }
                }
                
                // 关闭连接
                reader.close();
                writer.close();
                clientSocket.close();
                
                if (debug) {
                    Log.d(TAG, "客户端连接已关闭");
                }
                
                // 通知客户端断开连接
                if (callback != null) {
                    callback.onClientDisconnected();
                }
                
            } catch (IOException e) {
                Log.e(TAG, "处理客户端连接错误: " + e.getMessage());
                
                try {
                    clientSocket.close();
                } catch (IOException ex) {
                    Log.e(TAG, "关闭客户端Socket错误: " + ex.getMessage());
                }
                
                // 通知客户端断开连接
                if (callback != null) {
                    callback.onClientDisconnected();
                }
            }
        });
    }
    
    /**
     * 处理接收到的命令
     * @param command 命令字符串
     * @return 响应字符串
     */
    private String processCommand(String command) {
        // 命令格式：$TTFFLLDD...CC#
        if (command == null || command.isEmpty() || !command.startsWith("$") || !command.endsWith("#")) {
            return "ERROR:Invalid command format";
        }
        
        try {
            // 解析命令
            if (command.startsWith("$") && command.length() >= 8) {
                // 提取功能码
                String funcCodeStr = command.substring(3, 5);
                int funcCode = Integer.parseInt(funcCodeStr, 16);
                
                // 根据功能码处理命令
                switch (funcCode) {
                    case 0x11: // 小车运行
                        if (command.length() >= 12) {
                            int state = Integer.parseInt(command.substring(7, 9), 16);
                            int speed = Integer.parseInt(command.substring(9, 11), 16);
                            // 这里可以直接控制硬件，但在Android中通常不直接控制
                            return "OK:CAR_RUN";
                        }
                        break;
                        
                    case 0x12: // 舵机控制
                        if (command.length() >= 12) {
                            int servoId = Integer.parseInt(command.substring(7, 9), 16);
                            int angle = Integer.parseInt(command.substring(9, 11), 16);
                            return "OK:SERVO";
                        }
                        break;
                        
                    case 0x13: // LED控制
                        if (command.length() >= 16) {
                            int ledId = Integer.parseInt(command.substring(7, 9), 16);
                            int r = Integer.parseInt(command.substring(9, 11), 16);
                            int g = Integer.parseInt(command.substring(11, 13), 16);
                            int b = Integer.parseInt(command.substring(13, 15), 16);
                            return "OK:LED";
                        }
                        break;
                        
                    case 0x14: // 蜂鸣器
                        if (command.length() >= 10) {
                            int time = Integer.parseInt(command.substring(7, 9), 16);
                            return "OK:BUZZER";
                        }
                        break;
                        
                    default:
                        return "ERROR:Unknown function code";
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "处理命令错误: " + e.getMessage());
            return "ERROR:" + e.getMessage();
        }
        
        return "ERROR:Invalid command";
    }
    
    /**
     * 停止TCP服务器
     */
    public void stopTcpServer() {
        isServerRunning = false;
        
        if (serverSocket != null && !serverSocket.isClosed()) {
            try {
                serverSocket.close();
                if (debug) {
                    Log.d(TAG, "TCP服务器已停止");
                }
            } catch (IOException e) {
                Log.e(TAG, "停止TCP服务器错误: " + e.getMessage());
            }
        }
    }
    
    /**
     * 释放资源
     */
    public void release() {
        stopTcpServer();
        
        if (executorService != null) {
            executorService.shutdown();
        }
    }
}